<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Admin extends MY_Controller
{

    /* 构造 */
    public function __construct()
    {
        parent::__construct();
        $this->load->model('User');
        $this->load->model('UserCache');
        $this->load->model('UserPermission');
        $this->load->model('Permission');
        $this->load->model('TopicUnit');
        $this->load->model('WordDict');
    }

    /* 界面加载部分 */
    public function index()
    {}

    /* 显示用户信息 */
    public function userInfo()
    {
        $data = array();
        $userInfo = $this->session->user;
        $cache = $this->session->cache;
        $userInfo['state'] = $userInfo['state'] ? '已激活' : '未激活';
        $userInfo['create_time'] = date('Y-m-d H:i:s', $userInfo['create_time']);
        $userInfo['bindIp'] = $userInfo['is_bind_ip'] ? $userInfo['bind_ip'] : '未绑定';
        $userInfo['lastLoginIp'] = $cache['lastLoginIp'];
        $userInfo['lastLoginTime'] = $cache['lastLoginTime'];
        $userInfo['loginIp'] = $cache['loginIp'];
        $userInfo['loginTime'] = $cache['loginTime'];
        $data['userInfo'] = $userInfo;
        $this->load->view('admin/userInfo', $data);
    }

    /* 添加用户界面显示 */
    public function addUser()
    {
        $this->load->helper('form');
        $this->load->view('admin/addUser');
    }

    /* 编辑用户界面显示 */
    public function editUser($id)
    {
        $condition = array(
            'id' => $id
        );
        $result = $this->User->find($condition);
        $user = $result[0];
        $temp['id'] = $user['id'];
        $temp['username'] = $user['username'];
        $temp['email'] = $user['email'];
        $temp['isBindIp'] = $user['is_bind_ip'];
        $temp['bindIp'] = $user['bind_ip'];
        $temp['state'] = $user['state'];
        $data['user'] = $temp;
        $this->load->view('admin/editUser', $data);
    }

    /* 获取用户列表 */
    public function userList()
    {
        $data = array();
        $result = $this->User->find();
        foreach ($result as $v) {
            $temp['id'] = $v['id'];
            $temp['username'] = $v['username'];
            $temp['email'] = $v['email'];
            $temp['bindIp'] = $v['is_bind_ip'] ? $v['bind_ip'] : '未绑定';
            $temp['state'] = $v['state'] ? '已激活' : '未激活';
            $condition = array(
                'user_id' => $v['id']
            );
            $cache = $this->UserCache->find($condition);
            $temp['lastLoginIp'] = $cache[0]['last_login_ip'] ? $cache[0]['last_login_ip'] : '';
            $temp['lastLoginTime'] = $cache[0]['last_login_time'] ? date('Y-m-d H:i:s', $cache[0]['last_login_time']) : '';
            $user[] = $temp;
        }
        $data['user'] = $user;
        $this->load->view('admin/userList', $data);
    }

    /* 显示 */
    public function getUser($id)
    {
        $condition = array(
            'id' => $id
        );
        $result = $this->User->find($condition);
        $user = $result[0];
        $conditon = array(
            'user_id' => $id
        );
        $result = $this->UserCache->find($conditon);
        $cache = $result[0];
        $temp['username'] = $user['username'];
        $temp['email'] = $user['email'];
        $temp['bindIp'] = $user['is_bind_ip'] ? $user['bind_ip'] : '未绑定';
        $temp['state'] = $user['state'] ? '已激活' : '未激活';
        $temp['createTime'] = date('Y-m-d H:i:s', $user['create_time']);
        $temp['lastloginIp'] = $cache['last_login_ip'];
        $temp['lastloginTime'] = date('Y-m-d H:i:s', $cache['last_login_time']);
        $data['userInfo'] = $temp;
        $this->load->view('admin/getUser', $data);
    }

    /* 添加用户 */
    public function addUserOpt()
    {
        $this->load->library('form_validation');
        /* 获取参数初始化 */
        $data = array();
        $username = trim($this->input->post('username'));
        $email = trim($this->input->post('email'));
        $isBind = $this->input->post('bindIP');
        $userType = $this->input->post('userType');
        $password = md5(md5($username));
        $time = time();
        $userGroup = 1;
        $state = 1;
        
        /* 查看当前用户是否存在 */
        $condition = array(
            'username' => $username
        );
        $result = $this->User->find($condition);
        if (! empty($result)) {
            $data['code'] = 0;
            $data['msg'] = '该账户已经存在！';
            $this->load->view('admin/addUser', $data);
            return false;
        }
        
        /* 添加用户 */
        $value = array(
            'username' => $username,
            'password' => $password,
            'email' => $email,
            'is_bind_ip' => $isBind,
            'update_time' => $time,
            'create_time' => $time,
            'user_group' => $userGroup,
            'user_type' => $userType,
            'state' => $state
        );
        
        $result = $this->User->insert($value);
        if (! $result) {
            $data['code'] = 1;
            $data['msg'] = '添加失败！';
            $this->load->view('admin/addUser', $data);
            return false;
        }
        
        $data['code'] = 1;
        $data['msg'] = '添加成功！';
        
        /* 增加cach记录和UserPermission记录 */
        $result = $this->User->find($condition);
        $user = $result[0];
        if (empty($user)) {
            $error = "cache表和UserPermission插入失败：{$username}未找到";
            log_message('error', $error);
        } else {
            $value = array(
                'user_id' => $user['id']
            );
            $result1 = $this->UserCache->insert($value);
            $result2 = $this->UserPermission->insert($value);
        }
        
        $this->load->view('admin/addUser', $data);
    }

    /* 修改用户 */
    public function editUserOpt()
    {
        /* 获取参数初始化 */
        $username = $this->input->post('username');
        $email = $this->input->post('email');
        $isBind = $this->input->post('isBind');
        $bindIp = $this->input->post('bindIp');
        $state = $this->input->post('state');
        $time = time();
        $data = array(
            'code' => 0,
            'msg' => ''
        );
        
        $condition = array(
            'username' => $username
        );
        $value = array(
            'email' => $email,
            'is_bind_ip' => $isBind,
            'bind_ip' => $bindIp,
            'update_time' => $time,
            'state' => $state
        );
        $result = $this->User->update($condition, $value);
        if ($result) {
            $data['code'] = 1;
            $data['msg'] = '修改成功！';
        } else {
            $data['msg'] = '修改失败！';
        }
        $user = array(
            'username' => $username,
            'email' => $email,
            'isBindIp' => $isBind,
            'bindIp' => $bindIp,
            'state' => $state
        );
        $data['user'] = $user;
        $this->load->view('admin/editUser', $data);
    }

    /* 用户权限管理 */
    public function rootManage($id)
    {
        $data = array();
        $condition = array(
            'user_id' => $id
        );
        $result = $this->UserPermission->find($condition);
        $userPermission = $result[0]['permission_id'];
        $userPermission .= ",".$result[0]['topic_id'];
        $result = $this->Permission->find();
        $content = array('id'=>'content','parentId'=>0,'name'=>'知识库内容管理','children'=>[]);
        $content['children'][] = $this->getQuesTree(); 
        $content['children'][] = $this->getWordTree(); 
        $menuTree = $this->getChild(0, $result);
        foreach ($menuTree as $tr){
            if($tr['id']== 1){
                $tree[] = $tr;
                $tree[] = $content;
            }else{
                $tree[] = $tr; 
            }
        }

        
        
        
        $data['tree'] = json_encode($tree);
        $data['userid'] = $id;
        $data['userPermission'] = $userPermission;
        $this->load->view("admin/rootManage", $data);
    }

    /* 用户权限管理保存 */
    public function rootManageOpt()
    {
        $res = array(
            'code' => 0,
            'msg' => ''
        );
        $userid = $_REQUEST['userid'];
        $id = $_REQUEST['id'];
        $topicId = $_REQUEST['topicId'];
        $condition = array(
            'user_id' => $userid
        );
        $value = array(
            'permission_id' => $id,
            'topic_id'=> $topicId
        );
        $result = $this->UserPermission->update($condition, $value);
        if ($result) {
            $res['code'] = 1;
            $res['msg'] = '权限修改成功！';
        } else {
            $res['msg'] = '修改权限失败！';
        }
        echo json_encode($res);
    }

    /* 删除用户 */
    public function deleteUser()
    {
        $data = array(
            'code' => 0,
            'msg' => ''
        );
        $id = $this->input->post('id');
        $conditon = array(
            'id' => $id
        );
        $result = $this->User->delete($conditon);
        if ($result) {
            $data['code'] = 1;
            $data['msg'] = '删除成功！';
        } else {
            $data['msg'] = '删除失败！';
        }
        echo json_encode($data);
    }

    /* 重置密码 */
    public function resetPassword()
    {
        $time = time();
        $data = array(
            'code' => 0,
            'msg' => ''
        );
        $username = $this->input->post('username');
        $password = md5(md5($username));
        $condition = array(
            'username' => $username
        );
        $value = array(
            'password' => $password,
            'update_time' => $time
        );
        $result = $this->User->update($condition, $value);
        if ($result) {
            $data['code'] = 1;
            $data['msg'] = '重置密码成功！';
        } else {
            $data['msg'] = '重置密码失败！';
        }
        echo json_encode($data);
    }

    /* 修改密码界面加载 */
    public function setPassword()
    {
        $this->load->helper('form');
        $this->load->view('admin/setPassword');
    }

    /* 修改密码操作 */
    public function setPasswordOpt()
    {
        $data = array(
            'code' => 0,
            'msg' => ''
        );
        $this->load->library('form_validation');
        $password = md5(md5(trim($this->input->post('password'))));
        $newPassword = md5(md5(trim($this->input->post('newPassword'))));
        $user = $this->session->user;
        $username = $user['username'];
        $condition = array(
            'username' => $username,
            'password' => $password
        );
        $result = $this->User->find($condition);
        if (! $result) {
            $data['msg'] = '原始密码错误！';
            $this->load->view('admin/setPassword', $data);
            return false;
        }
        $condition = array(
            'username' => $username
        );
        $value = array(
            'password' => $newPassword
        );
        $result = $this->User->update($condition, $value);
        if ($result) {
            $data['code'] = 1;
            $data['msg'] = '修改成功！';
            $this->session->sess_destroy();
        } else {
            $data['msg'] = '修改失败！';
        }
        $this->load->view('admin/setPassword', $data);
    }

    /* 获取子节点 */
    private function getChild($pid, $data)
    {
        $tree = array();
        foreach ($data as $k => $v) {
            if ($v['pid'] == $pid) {
                unset($data[$k]);
                $tmp = array();
                $tmp['id'] = $v['id'];
                $tmp['parentId'] = $v['pid'];
                $tmp['name'] = $v['name'];
                $tmp['children'] = $this->getChild($v['id'], $data);
                $tree[] = $tmp;
            }
        }
        return $tree;
    }
    
    private function getQuesTree(){
        $rootUnits = $this->TopicUnit->find(array('parents'=>'ROOT','is_valid'=>true));
        $tree = array('id'=>'unit','parentId'=>'content','name'=>'问答库内容','children'=>[]);
        foreach($rootUnits as $rootUnit){
            $unit = array('id'=>$rootUnit['_id'],'parentId'=>'unit','name'=>$rootUnit['topic_name'],'children'=>[]);
            $tree['children'][] = $unit;
        }
        return $tree;
    }
    private function getWordTree(){
        $rootWords = $this->WordDict->find(array('full_type'=>'ROOT','is_valid'=>true));
        $tree = array('id'=>'word','parentId'=>'content','name'=>'词库内容','children'=>[]);
        foreach($rootWords as $rootWord){
            $unit = array('id'=>$rootWord['_id'],'parentId'=>'word','name'=>$rootWord['word'],'children'=>[]);
            $tree['children'][] = $unit;
        }
        return $tree;
    }
}